package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qk.common.PageResult;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.domain.user.UserDO;
import com.qk.dto.user.UserDto;
import com.qk.dto.user.UserLoginDto;
import com.qk.entity.Role;
import com.qk.management.mapper.RoleMapper;
import com.qk.vo.user.LoginResultVo;
import com.qk.entity.User;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.UserService;
import com.qk.common.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/*
 *  @author SHCJ
 *  @created 2025/10/6 12:49
 *  @description
 */
@Service
public class UserServiceImpl implements UserService {
     @Autowired
     private UserMapper userMapper;
     @Autowired
     private RoleMapper roleMapper;

     private static final Integer LOGIN_STATUS_UNNORMAL = 0;

     @Override
     public PageResult<UserDO> page(UserDto userDto) {
          PageHelper.startPage(userDto.getPage(), userDto.getPageSize());
          List<UserDO> list = userMapper.page(userDto);

//          对手机号进行脱敏
          for(UserDO userDO:list){
               userDO.setPhone(DesensitizedUtil.mobilePhone(userDO.getPhone()));
          }
          PageInfo<UserDO> pageInfo = new PageInfo<>(list);
          return new PageResult<>(pageInfo.getTotal(), pageInfo.getList());
     }

     @Override
     public void addUser(UserDO userDO) {
          // 参数校验： 工具类处理 hutool 工具类
          boolean hasNull = BeanUtil.hasNullField(userDO, "id", "password", "roleId", "deptId", "image", "remark", "updateTime", "createTime", "deptName", "roleName", "roleLabel");
          if (hasNull) {
               CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
          }


          userDO.setPassword(DigestUtils.md5DigestAsHex((userDO.getUsername()+"123").getBytes()));
          userDO.setCreateTime(LocalDateTime.now());
          userDO.setUpdateTime(LocalDateTime.now());
          userMapper.addUser(userDO);
     }

     @Override
     public void deleteByIds(List<Integer> ids) {
          userMapper.deleteByIds(ids);
     }

     @Override
     public Object findById(Integer id) {

          return userMapper.selectById(id);
     }

     @Override
     public void update(User user) {
          user.setUpdateTime(LocalDateTime.now());
          userMapper.update(user);
     }

     @Override
     public List<User> selectAll() {
          return userMapper.selectAll();
     }

     @Override
     public List<User> selectByRole(String roleLabel) {
          return userMapper.selectByRole(roleLabel);
     }

     @Override
     public List<User> selectByDept(Integer deptId) {
          return userMapper.selectByDept(deptId);
     }

     @Override
     public LoginResultVo login(UserLoginDto userLoginDto) {
          // 1. 参数合法性校验
          boolean hasNull = BeanUtil.hasNullField(userLoginDto);
          if (hasNull){
               CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
          }
          // 2. 根据用户名查询数据库获取用户对象
          User user = userMapper.selectByUsername(userLoginDto.getUsername());
          // 3. 数据合法性校验
          if (Objects.isNull(user)){
               CommonException.throwCommonException(ParamEnum.LOGIN_USERNAME_ERROR);
          }

          // 4. 密码校验
          // 4.1获取前端用户传递密码,对其进行MD5
          String userPassword = DigestUtils.md5DigestAsHex(userLoginDto.getPassword().getBytes());
          String encodedPassword = user.getPassword();
          boolean isChecked = ObjectUtil.equals(userPassword, encodedPassword);
          if (!isChecked){
               CommonException.throwCommonException(ParamEnum.LOGIN_PASSWORD_ERROR);
          }
          // 4.2判断用户是否被禁用
          if (ObjectUtil.equals(user.getStatus(), LOGIN_STATUS_UNNORMAL)){
               CommonException.throwCommonException(ParamEnum.LOGIN_STATUS_ERROR);
          }
//          5.获取role的roleLabel
          Role role = roleMapper.selectById(user.getRoleId());

//          6.返回封装的数据
          return LoginResultVo.builder()
                  .id(user.getId())
                  .username(user.getUsername())
                  .name(user.getName())
                  .image(user.getImage())
                  .roleLabel(role.getLabel())
//                  TODO 生成token
                  .token(JwtUtils.generateToken(Map.of("id", user.getId(), "username", user.getUsername())))
                  .build();
     }
}
